from flask import jsonify, request, Response
from supermarket.app import app, db, redis_store
from supermarket.app.models import Employee
import csv
from io import StringIO


# 员工管理的CRUD操作
@app.route('/employees', methods=['GET'])
def get_employees():
    try:
        employees = Employee.query.all()
        serialized_employees = [employee.to_dict() for employee in employees]
        return jsonify(serialized_employees), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 400


@app.route('/employees/<int:id>', methods=['GET'])
def get_employee(id):
    try:
        employee = Employee.query.get_or_404(id)
        serialized_employee = employee.to_dict()
        return jsonify(serialized_employee), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 400


@app.route('/employees', methods=['POST'])
def create_employee():
    try:
        data = request.get_json()
        new_employee = Employee(**data)
        db.session.add(new_employee)
        db.session.commit()
        return jsonify(new_employee.to_dict()), 201
    except Exception as e:
        return jsonify({'error': str(e)}), 400


@app.route('/employees/<int:id>', methods=['PUT'])
def update_employee(id):
    try:
        employee = Employee.query.get_or_404(id)
        data = request.get_json()
        for key, value in data.items():
            setattr(employee, key, value)
        db.session.commit()
        return jsonify(employee.to_dict()), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 400


@app.route('/employees/<int:id>', methods=['DELETE'])
def delete_employee(id):
    try:
        employee = Employee.query.get_or_404(id)
        db.session.delete(employee)
        db.session.commit()
        return jsonify({'message': 'Employee deleted'}), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 400


# 导出CSV
@app.route('/employees/export/csv', methods=['GET'])
def export_employees_csv():
    try:
        employees = Employee.query.all()
        output = StringIO()
        writer = csv.writer(output)
        # 写入CSV头部
        writer.writerow(['id', 'name', 'password', 'level', 'phone', 'salary', 'remark'])
        # 写入CSV行
        for employee in employees:
            writer.writerow([employee.id, employee.name, employee.password, employee.level, employee.phone,
                             employee.salary, employee.remark])
        output.seek(0)
        return Response(output, mimetype='text/csv', headers={'Content-Disposition': 'attachment; filename=employees.csv'}), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 400
